/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.safetytask.service.impl;

import com.koron.audit.approval.AfterApprovalService;
import com.koron.audit.domain.Audit;
import com.koron.audit.management.FlowManagement;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.safetytask.domain.JobsTasks;
import com.koron.safetytask.mapper.JobsTasksMapper;
import com.koron.safetytask.service.api.JobsTasksService;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.util.*;

@Service
public class JobsTasksServiceImpl implements JobsTasksService, AfterApprovalService, InitializingBean {

    @Autowired
    private FlowManagement flowManagement;

    private final static Logger logger= LoggerFactory.getLogger(JobsTasksServiceImpl.class);

    @SuppressWarnings("deprecation")
    @Override
    public MessageBean<?> submit(StaffBean user, String id, String nextLeaderCode, String title, String note, MultipartFile file) {
        MessageBean<?> msg = MessageBean.create(0, "SUCCESS", void.class);
        SessionFactory factory = new SessionFactory();
        try {
            JobsTasks task = factory.getMapper(JobsTasksMapper.class).queryById(id);
            if (task == null) {
                factory.close();
                msg.setCode(35003);
                msg.setDescription("任务不存在");
                return msg;
            }

            //启动流程
            Audit audit = new Audit(title, note, user.getName(), new Date());
            audit.setId(DefaultIdGenerator.getInstance().generateLongId());
            audit.setTitle(title);
            audit.setDescription(note);
            audit.setInitiatorCode(user.getCode());
            audit.setTarget("JobsTasksServiceImpl");
            audit.setTemplateKey("dev_test");
            audit.setOperation(1);
            audit.setState(1);
            audit.setFlowType(1);
            audit.setFlowName("任务提交");
            Map<String, Object> map = new HashMap<>();
            if (!StringUtils.isEmpty(nextLeaderCode)) {
                map.put("nextLeaderCode", nextLeaderCode);
            }
            audit.setBusinessIds(id);
            if (!flowManagement.initFlow(user, audit, map)) {
                msg.setCode(35003);
                msg.setDescription("流程启动失败");
                factory.close();
                return msg;
            }
            task.setCompletedTime(new Date());
            task.setFstatusflag(1);
            factory.getMapper(JobsTasksMapper.class).completed(task);
            factory.close();
            msg.setDescription("提交成功");
        } catch (Exception e) {
            factory.close(false);
            msg.setCode(35003);
            msg.setDescription("流程启动失败");
        }
        return msg;
    }

    @SuppressWarnings({"rawtypes", "unchecked", "deprecation"})
    @Override
    public MessageBean<?> list(String staffCode, String staffName, String taskType, String router, Integer state, Date begin, Date end, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(0, "SUCCESS", DataBean.class);
        Integer totalPage = null;
        Integer totalNumber = null;
        Integer start = null;
        Integer row = null;
        if (null != page && pageSize != null) {
            if (page > 0 && pageSize > 0) {
            } else {
                //第一页 10条数据
                page = 1;
                pageSize = 10;
            }
            start = (page <= 1) ? 0 : (page - 1) * pageSize;
            row = pageSize;
        }
        try (SessionFactory factory = new SessionFactory();) {
            List<String> typeIdList = new ArrayList<>();
            if (StringUtils.isEmpty(router) && StringUtils.isEmpty(taskType)) {
                typeIdList = null;
            } else {
                if (!StringUtils.isEmpty(router)) {
                    typeIdList = factory.getMapper(JobsTasksMapper.class).typeListByRouter(router);
                }
                if (!StringUtils.isEmpty(taskType)) {
                    typeIdList.add(taskType);
                }
                if (typeIdList.isEmpty()) {
                    typeIdList.add("");
                }
            }
            totalNumber = factory.getMapper(JobsTasksMapper.class).count(staffCode, staffName, typeIdList, state, begin, end);
            if (start != null && end != null) {
                totalPage = (totalNumber + pageSize - 1) / pageSize;
            } else {
                totalPage = 1;
                page = totalPage;
                pageSize = totalNumber;
            }
            DataBean data = new DataBean();
            data.setList(queryList(staffCode, staffName, typeIdList, state, begin, end, start, row));
            data.setPageNo(page);
            data.setPageSize(pageSize);
            data.setTotalNumber(totalNumber);
            data.setTotalPage(totalPage);
            msg.setData(data);
        } catch (Exception e) {
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }
        return msg;
    }

    @Override
    public MessageBean<?> details(String id) {
        MessageBean<JobsTasks> msg = MessageBean.create(0, "SUCCESS", JobsTasks.class);
        SessionFactory factory = new SessionFactory();
        try {
            JobsTasks jobsTasks = factory.getMapper(JobsTasksMapper.class).getOne(id);
            msg.setData(jobsTasks);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(35001);
            msg.setDescription("数据库连接异常");
            return msg;
        }finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }

    @SuppressWarnings({"deprecation"})
    List<JobsTasks> queryList(String staffCode, String staffName, List<String> typeIdList, Integer state, Date begin, Date end, Integer start, Integer row) {
        List<JobsTasks> list = new ArrayList<>();
        try (SessionFactory factory = new SessionFactory()) {
            list = factory.getMapper(JobsTasksMapper.class).queryByStaff(staffCode, staffName, typeIdList, state, begin, end, start, row);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return list;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map map = flowManagement.getHandlers();
        map.put("JobsTasksServiceImpl", this);
    }

    @Override
    public void editApproval(Audit audit) {
        String id = audit.getBusinessIds();
        if (!StringUtils.isEmpty(id)) {
            try (SessionFactory factory = new SessionFactory()) {
                JobsTasks task = factory.getMapper(JobsTasksMapper.class).queryById(id);
                if (task != null) {
                    task.setState(1);
                    task.setFstatusflag(2);
                    factory.getMapper(JobsTasksMapper.class).completed(task);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(),e);
            }
        }
    }

    @Override
    public void discardApproval(Audit audit) {
        // TODO Auto-generated method stub
    }

    @Override
    public void processDiscard(Audit audit) {

    }

    @Override
    public void reject(Audit audit, List<String> userIdList) {
        // TODO 流程驳回操作
    }

    @Override
    public void passApproval(Integer operation, Audit audit) {
        // TODO 流程提交成功操作
    }
}
